import cv2
import time
import yaml
import logging
import keyboard  # 导入 keyboard 库
from image_utils import capture_screen, match_images
from mouse_utils import mouse_left_click

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def load_config():
    """加载配置文件"""
    with open('config/config.yaml', 'r') as f:
        config = yaml.safe_load(f)
    return config

def main():
    config = load_config()
    target_image_path = config['target_image_path']
    threshold = config['threshold']

    # 加载目标图片
    target_image = cv2.imread(target_image_path)

    # 定义一个变量来标记是否退出程序
    exit_program = False

    # 定义一个回调函数，用于处理 F10 按键事件
    def on_f10_pressed():
        nonlocal exit_program
        exit_program = True
        logging.info("F10 被按下，程序即将退出...")

    # 监听 F10 按键
    keyboard.add_hotkey('f10', on_f10_pressed)

    while True:
        if exit_program:
            break  # 退出循环

        # 截取屏幕
        screen_image = capture_screen()
        # 匹配图片
        matched, location = match_images(screen_image, target_image, threshold)
        if matched:
            x, y = location
            # 点击图片中心位置
            mouse_left_click(x, y)
            # 输出点击成功的日志信息
            logging.info(f"点击到图片，位置：({x}, {y})")
            # 休息1秒
            time.sleep(1)
        else:
            logging.info("未检测到目标图片，继续检测...")
            time.sleep(1)

if __name__ == "__main__":
    main()